/*
 * @Description : 加载地图方法
 */
import axios from 'axios';

/**
   * @param {String} mapKey 地图key
   */
export function loadTMap(mapKey:String, loadFlag?:any) {
  return new Promise(function(resolve, reject) {
    // console.log('123');
    // if(loadFlag) {
    //   loadScript(mapKey);
    // }
    // if (typeof TMap !== 'undefined') {
    //   resolve(TMap);
    //   return true;
    // }
    let promiseArr = [];
    let scriptArr = [`https://map.qq.com/api/gljs?v=1.exp&callback=onTMapCallback&key=${mapKey}`];
    if(loadFlag) {
      // 加载多边形画线工具
      let scriptSrc = `https://map.qq.com/api/gljs?v=1.exp&callback=onTMapCallback&libraries=geometry,tools,service&key=${mapKey}`;
      scriptArr.push(scriptSrc);
    }
    for (let i = 0; i < scriptArr.length; i++) {
      promiseArr.push(new Promise((resolve, reject) => {
        let script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = scriptArr[i];
        script.onerror = reject;
        document.head.appendChild(script);
        (window as any).onTMapCallback= function() {
          resolve(TMap);
        };
      }));
    }
    Promise.all(promiseArr).then(_res => {
      resolve(TMap);
    }).catch(err => {
      reject(err);
    });
  });
}

// 加载多边形画线工具
export function loadScript(mapKey:string) {
  let script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://map.qq.com/api/gljs?&&callback=onTMapCallback&libraries=geometry&v=1.exp&key=' + mapKey;
  document.head.appendChild(script);
  script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://map.qq.com/api/gljs?libraries=tools&v=1.exp&key=' + mapKey;
  document.head.appendChild(script);
  script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://map.qq.com/api/gljs?&libraries=service&v=1.exp&key=' + mapKey;
  document.head.appendChild(script);
}

//逆地址解析
export function parseAddress(lng:string, lat:string) {
  return new Promise((resolve, reject) => {
    let url = 'https://apis.map.qq.com/ws/geocoder/v1/';
    url += '?key=自己的腾讯mapkey';
    url += '&location=' + lng + ',' + lat;
    axios.get(url).then((res:any) => {
      resolve(res.result || {});
    }).catch(e => {
      reject(e);
    });
  });
}
export default {loadTMap, parseAddress};